﻿#region 命名空间

using System;
using System.IO;
using System.Web;
using System.Data;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Reflection;
using WinnerCMS.Data;
using WinnerCMS.Common;
using WinnerCMS.Model;

#endregion

namespace WinnerCMS.BLL
{
    /// <summary>
    /// AdsManage 的摘要说明。
    /// </summary>
    public class AdsManage : MarshalByRefObject
    {
        private static readonly AdvertDal Dal = new AdvertDal();

        /// <summary>
        /// 绑定数据
        /// </summary>
        /// <param name="action"></param>
        /// <param name="pp"></param>
        /// <returns></returns>
        public IList<Advert> BindList(string action, PagingParam pp)
        {
            return Dal.BindList(action, pp);
        }

        #region 保存广告

        /// <summary>
        /// 保存广告
        /// </summary>
        /// <param name="model"></param>
        [Logging("保存广告：{@p0.ID}"), ExceptionCall]
        public Result Save(Advert model)
        {
            Result res = new Result();
            if (model.Id == 0)
            {
                model.UpDateTime = DateTime.Now;
                Dal.Add(model);
            }
            else
            {
                model.UpDateTime = DateTime.Now;
                Dal.Edit(model);
                try
                {
                    MakeJs(model.Id);
                }
                catch
                {
                    res.Errors = "生成JS文件失败，可能没有写入硬盘的权限。";
                }
            }
            return res;
        }

        #endregion

        /// <summary>
        /// 暂停或者启动广告
        /// </summary>
        /// <param name="id"></param>
        [Logging("暂停或者启动广告：{@p0.ID}"), ExceptionCall]
        public Result StopOrOpen(string id)
        {
            Result res = new Result();
            Dal.StopOrOpen(int.Parse(id));
            MakeJs(int.Parse(id)); //先试图生成一个再删除
            DeleteJS(id);

            return res;
        }

        /// <summary>
        /// 删除广告
        /// </summary>
        /// <param name="id"></param>
        [Logging("删除广告，ID：{@p0.ID}"), ExceptionCall]
        public Result Delete(string id)
        {
            Result res = new Result();
            Dal.Delete(int.Parse(id));
            DeleteJS(id);

            return res;
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public Advert GetInfo(string ID)
        {
            return Dal.GetInfo(int.Parse(ID));
        }

        #region 生成广告JS

        /// <summary>
        /// 生成广告JS
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public void MakeJs(int id)
        {
            Advert model = GetInfo(id.ToString());
            string jsCode = "";
            string hostUrl = HttpContext.Current.Request.ServerVariables["http_host"];
            hostUrl = "Http://" + hostUrl;
            string scrCode = "";
            if (model.Url.Length == 0)
            {
                scrCode = "<EMBED src=" + model.AdUrl + " quality=high WIDTH=" + model.Width + " HEIGHT=" + model.Height +
                          " TYPE=application/x-shockwave-flash PLUGINSPAGE=http://www.macromedia.com/go/getflashplayer></EMBED>";
            }
            else
            {
                scrCode = "<a href=" + hostUrl + "/AdsClick.ashx?ID=" + id + "&Go=" + model.Url + " target=" +
                          model.Target + "><img src=" + model.AdUrl + " border=0 width=" + model.Width + " height=" +
                          model.Height + " alt=" + model.Note + " align=top></a>";
            }
            switch (model.ShowType)
            {
                case 1:
                    jsCode = "document.write('" + scrCode + "');";
                    break;
                case 2:
                    jsCode +=
                        "document.write('<DIV id=img1 style=\"Z-INDEX: 100; LEFT: 2px; WIDTH: 59px; POSITION: absolute; TOP: 43px; HEIGHT: 61px; visibility: visible;\">";
                    jsCode += scrCode + "</DIV>');";
                    jsCode += "document.write('<script language=javascript src=" + hostUrl +
                              "/images/GGJS/TWGG_float_fullscreen.js></script>');";

                    break;
                case 3:

                    jsCode += "if (navigator.appName == 'Netscape')";
                    jsCode += "{document.write('<layer id=DGbanner3 top=150 width=" + model.Width + " height=" +
                              model.Width + ">" + scrCode + "</layer>');}";
                    jsCode += "else{document.write('<div id=DGbanner3 style=\"position: absolute;width:" + model.Width +
                              ";top:150;visibility: visible;z-index: 1\">" + scrCode + "</div>');}";
                    jsCode += "document.write('<script language=javascript src=" + hostUrl +
                              "/images/GGJS/TWGG_float_upanddown.js></script>');";
                    break;
                case 4:
                    jsCode += "ns4=(document.layers)?true:false;";
                    jsCode +=
                        "if(ns4){document.write('<layer id=DGbanner4Cont onLoad=\"moveToAbsolute(layer1.pageX-160,layer1.pageY);clip.height=" +
                        model.Height + ";clip.width=" + model.Width +
                        "; visibility=show;\"><layer id=DGbanner4News position:absolute; top:0; left:0>" + scrCode +
                        "</layer></layer>');}";
                    jsCode +=
                        "else{document.write('<div id=DGbanner4 style=\"position:absolute;top:0; left:0;\"><div id=DGbanner4Cont style=\"position:absolute; width:" +
                        model.Width + "; height:" + model.Width + ";clip:rect(0," + model.Width + "," + model.Width +
                        ",0)\"><div id=DGbanner4News style=\"position:absolute;top:0; left:0; right:820\">" + scrCode +
                        "</div></div></div>');} ";
                    jsCode += "document.write('<script language=javascript src=" + hostUrl +
                              "/images/GGJS/TWGG_fullscreen.js></script>');";
                    break;
                case 5:
                    jsCode = "window.showModalDialog('" + model.Url + "','','dialogWidth:" + model.Width +
                             "px;dialogHeight:" + model.Width + "px;scroll:no;status:no;help:no');";
                    break;
                case 6:
                    jsCode = GetResourceContents("ad-06.js");
                    jsCode = jsCode.Replace("{0}", scrCode);


                    break;
                case 7:
                    jsCode = "window.open('" + model.Url + "','_blank');";
                    break;
                case 8:
                    jsCode = "window.open('" + model.Url + "','DGBANNER7','width=" + model.Width + ",height=" +
                             model.Height + ",scrollbars=1')";
                    break;
            }

            string strFileName = HttpContext.Current.Server.MapPath("~/JS/JsAd" + id + ".js");

            new FileIO().WriterFile(strFileName, jsCode);
        }

        /// <summary>
        /// 读取资源文件
        /// </summary>
        /// <param name="resourceName"></param>
        /// <returns></returns>
        private string GetResourceContents(string resourceName)
        {
            string text1 = string.Empty;
            string text2 = Assembly.GetExecutingAssembly().GetName().Name;
            Stream stream1 = Assembly.GetExecutingAssembly().GetManifestResourceStream(text2 + ".Ads." + resourceName);
            if (stream1 != null)
            {
                StreamReader reader1 = new StreamReader(stream1);
                try
                {
                    text1 = reader1.ReadToEnd();
                }
                catch
                {
                }
                finally
                {
                    reader1.Close();
                }
            }
            return text1;
        }

        #endregion

        /// <summary>
        /// 广告点击
        /// </summary>
        /// <param name="id"></param>
        public void Click(string id)
        {
            Dal.Click(int.Parse(id));
        }

        /// <summary>
        /// 删除广告JS
        /// </summary>
        /// <param name="ID"></param>
        private void DeleteJS(string ID)
        {
            string strFileName = HttpContext.Current.Server.MapPath("~/JS/JsAd" + ID + ".js");
            File.Delete(strFileName);
        }
    }
}